package com.erp.erp_servers.Cost.imp;

import com.erp.erp_dao.Cost.CostDao;
import com.erp.erp_entitys.Cost.entity.CostEntity;
import com.erp.erp_entitys.Cost.req.*;
import com.erp.erp_entitys.Cost.vo.*;
import com.erp.erp_entitys.warehouse.entity.AnnexEntity;
import com.erp.erp_servers.Cost.CostService;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zjk
 * @version 1.0
 * @description 费用具体实现
 * @date 2020/11/17/017 22:23
 */
@Service
public class CostServiceImpl implements CostService {


    private final CostDao costDao;
    //使用构造器注入,提高安全性
    @Autowired
    public CostServiceImpl(CostDao costDao) {
        this.costDao = costDao;
    }

    @Override
    public PageInfo<CostEntity> findAllCost(QueryCostReq req) {
        List<CostEntity> costEntities= costDao.findAll(req);
        PageInfo<CostEntity> costEntityPageInfo=new PageInfo<CostEntity>(costEntities);
        return costEntityPageInfo;
    }

    @Override
    public PageInfo<QueryCostRes> findAllQueryCostRes(QueryCostReq req) {
        List<QueryCostRes> costEntities= costDao.findAllQueryCostRes(req);
        for (QueryCostRes p:costEntities) {
            p.setTotalCostCreateTimeStr(DateUtils.format(p.getTotalCostCreateTime(),DateUtils.DATE_PATTERN));
        }
        PageInfo<QueryCostRes> costEntityPageInfo=new PageInfo<>(costEntities);
        return costEntityPageInfo;
    }

    @Override
    public CostEntity selectByPrimaryKey(String code) {
        return costDao.selectByPrimaryKey(code);
    }

    @Override
    public int updateByCostEntity(CostEntity costEntity) {
        return costDao.updateByCostEntity(costEntity);
    }

    @Override
    public int updateCostAndTime(BigDecimal totalCost, Date totalCostCreateTime, String code) {
        return costDao.updateCostAndTime(totalCost, totalCostCreateTime, code);
    }

    /**
     * 这个操作有问题，如果从数据库删除数据呢
     * 建议查询数据库排序得到最后一个编号，根据最后一个编号计算可以添加的编号
     * @return
     */
    @Override
    public String selectCodeByCode() {
       //String date= DateUtils.format(new Date(),"YYYY-MM-dd");
        LocalDate date=LocalDate.now();
        int count=costDao.selectCodeByCode(date);
        int number=count+1;
        //这一步主要是数字格式，使之格式成为“001”
        DecimalFormat df=new DecimalFormat();
        df.setMinimumIntegerDigits(3);

        String dateStr=date.format(DateTimeFormatter.ofPattern("YYYYMMdd"));
        String codeStr="IN-RTCO"+dateStr+df.format(number);
        return codeStr;

    }

    //-------------------------------------------------------
    @Override
    public List<QueryBillCompanyVO> selectCompanyForBillCompanyCode() {
        return costDao.selectCompanyForBillCompanyCode();
    }
    @Override
    public QueryBillCompanyVO selectCompanyForBillCompanyCode2(String BillCompanyCode) {
        return costDao.selectCompanyForBillCompanyCode2(BillCompanyCode);
    }

    @Override
    public List<QueryPayeeVO> selectCustomer2ForPayee() {
        return costDao.selectCustomer2ForPayee();
    }

    @Override
    public List<QueryPayeeVO> selectCustomer2ForPayee(String payeeCode) {
        List<QueryPayeeVO> payeeVOS=costDao.selectCustomer2ForPayee(payeeCode);
        for (QueryPayeeVO s:payeeVOS){
            System.out.println(s.toString());
        }
        return payeeVOS;
    }

    @Override
    public List<QueryPayeeBankVO>  selectPayeeBankName(String payeeCode){
        return costDao.selectPayeeBankName(payeeCode);
    }
    @Override
    public List<QueryPayeeBankVO>  selectPayeeBankAccount(String bankName,String payeeCode){
        return costDao.selectPayeeBankAccount(bankName,payeeCode);
    }

    @Override
    public String selectPayeeBankAccountName(String payeeCode, String bankAccount) {
        return costDao.selectPayeeBankAccountName(payeeCode,bankAccount);
    }

    @Override
    public List<QueryPayeeVO2> selectPayeeBankInfo() {
        return costDao.selectPayeeBankInfo();
    }

    @Override
    public List<QueryDeptVO>  selectDeptByAcc(QueryDeptAccReq deptAccReq){
        List<QueryDeptVO> deptVOS= costDao.selectDeptByAcc(deptAccReq);

        return deptVOS;
    }
    @Override
    public List<QueryDeptVO2>  selectDept(){
        List<QueryDeptVO2> deptVOS= costDao.selectDept();

        List<QueryDeptVO2> deptList=new ArrayList<>(deptVOS.size()*2);
        for (int i = 0; i <deptVOS.size() ; i++) {//公司
            QueryDeptVO2 p=deptVOS.get(i);
            if (StringUtils.isEmpty(p.getCompanyCode())){//部门
                for (int j = 0; j <deptVOS.size() ; j++) {
                    QueryDeptVO2 pp=deptVOS.get(j);
                    if (StringUtils.isNotEmpty(pp.getCompanyCode()) && pp.getCompanyCode().equals(p.getDepartmentCode())){
//                        deptVOS.remove(p);
//                        deptList.add(p);
                        //添加部门
                        deptList.add(pp);
                    }
                }
            }

        }

        A:for (int i = 0; i <deptVOS.size() ; i++) {
            QueryDeptVO2 p=deptVOS.get(i);
            //添加公司
            for (int j = 0; j <deptList.size() ; j++) {
                QueryDeptVO2 pp=deptList.get(j);
                if (p.getDepartmentCode().equals(pp.getCompanyCode())){
                    deptList.add(p);
                    continue A;
                }
            }
        }

        return deptList;
    }

    @Override
    public List<QueryAccVO>  selectAccByDept(QueryDeptAccReq deptAccReq){
        return costDao.selectAccByDept(deptAccReq);
    }
    @Override
    public List<QueryAccVO2>  selectAcc(){
        return costDao.selectAcc();
    }
    @Override
    public List<QueryAccVO2>  getAccByDeptCode(String deptCode){
        return costDao.selectAccByDeptCode(deptCode);
    }
    @Override
    public List<DictionaryCostFeeVO> getDictionaryCosFee(DictionaryCostReq req){
        return costDao.getDictionaryCostFee(req);
    }
    //-------------------------------------------------------



    @Override
    public PageInfo<QueryImportInvoiceVO> selectInvoiceByInvoiceTypeOne(QueryImportInvoiceReq importInvoiceReq) {
        List<QueryImportInvoiceVO> queryImportInvoiceVOS=costDao.selectInvoiceByInvoiceTypeOne(importInvoiceReq);
        for (QueryImportInvoiceVO p:queryImportInvoiceVOS) {
            p.setInvoiceDateStr(DateUtils.format(p.getInvoiceDate(),DateUtils.DATE_PATTERN));
        }
        PageInfo pageInfo=new PageInfo(queryImportInvoiceVOS);
        return pageInfo;
    }

    @Override
    public PageInfo<QueryImportInvoiceVO> selectInvoiceByInvoiceTypeTwo(QueryImportInvoiceReq importInvoiceReq) {
        List<QueryImportInvoiceVO> queryImportInvoiceVOS=costDao.selectInvoiceByInvoiceTypeTwo(importInvoiceReq);
        for (QueryImportInvoiceVO p:queryImportInvoiceVOS) {
            p.setInvoiceDateStr(DateUtils.format(p.getInvoiceDate(),DateUtils.DATE_PATTERN));
        }
        PageInfo pageInfo=new PageInfo(queryImportInvoiceVOS);
        return pageInfo;
    }

    @Override
    public PageInfo<QueryImportContractVO> selectExportContractByPrimary(QueryImportContractReq importContractReq) {
        List<QueryImportContractVO> queryImportContractVOS=costDao.selectContractByPrimary(importContractReq);
        for (QueryImportContractVO p:queryImportContractVOS) {
            p.setSigningDateStr(DateUtils.format(p.getSigningDate(),DateUtils.DATE_PATTERN));
        }
        PageInfo pageInfo=new PageInfo(queryImportContractVOS);
        return pageInfo;
    }

    @Override
    public PageInfo<QueryImportContractVO> selectPurchaseContractByPrimary(QueryImportContractReq importContractReq) {

        List<QueryImportContractVO> queryImportContractVOS=costDao.selectPurchaseContractByPrimary(importContractReq);
        for (QueryImportContractVO p:queryImportContractVOS) {
            p.setSigningDateStr(DateUtils.format(p.getSigningDate(),DateUtils.DATE_PATTERN));
        }
        PageInfo pageInfo=new PageInfo(queryImportContractVOS);
        return pageInfo;
    }

    @Override
    public PageInfo<QueryImportResourceSamplesVO> selectResourceSamplesByPrimary(QueryImportResourceSamplesReq req) {
        List<QueryImportResourceSamplesVO> queryImportInvoiceVOS=costDao.selectResourceSamplesByPrimary(req);
        for (QueryImportResourceSamplesVO p:queryImportInvoiceVOS) {
            p.setCreateDateStr(DateUtils.format(p.getCreateDate(),DateUtils.DATE_PATTERN));
        }
        PageInfo pageInfo=new PageInfo(queryImportInvoiceVOS);
        return pageInfo;
    }

    @Override
    public List<QueryAllUserVO> selectAllUser() {
        return costDao.selectAllUser();
    }

    @Override
    public int insertSelective(CostEntity cost) {
        return costDao.insertSelective(cost);
    }

    @Override
    public Integer updateCostStatus(Integer costId) {
        //修改主费用为无效
        return costDao.updateCostStatus(costId);
    }

    @Override
    public Integer delCostByCostId(Integer costId) {
        return costDao.delCostByCostId(costId);
    }

    @Override
    public CostEntity findCostById(Integer costId) {
        return costDao.findCostById(costId);
    }

    @Override
    public int updateCostTypeByCostId(Integer[] costId, Integer status) {
        return costDao.updateCostTypeByCostId(costId,status);
    }
    @Override
    public R updateCostStatusDustbinToDrafts(Integer costId) {
        int num=costDao.updateCostStatusDustbinToDrafts(costId);
        if (num>0){
            return R.build(ResultStatusEnum.SUCCESS);
        }
        return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
    }

    @Override
    public Integer updateAnnexValid(List<Integer> ids, Integer valid) {
        return costDao.updateAnnexValid(ids, valid);
    }

    @Override
    public AnnexEntity selectAnnexById(Integer annexId) {
        return costDao.selectAnnexById(annexId);
    }


    //**********************************费用申请，工作流开始********************************************************

    @Override
    public R updateCostStatusByCostId(UpdateCostStatusBpmReq req) {
        int num=costDao.updateCostStatusByCostId(req);
        if (num>0){
            return R.build(ResultStatusEnum.SUCCESS);
        }
        return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
    }

    @Override
    public boolean updateStatus(String costId, String bpmStatus) {
        UpdateCostStatusBpmReq req=new UpdateCostStatusBpmReq();
        req.setId(Integer.parseInt(costId));
        req.setCostBpmStatus(bpmStatus);
        switch (bpmStatus){
            case "1"://待审批，待批箱
                req.setStatus("2");
                break;
            case "2"://审批完成，已批箱
                req.setStatus("3");
        }

        return costDao.updateCostStatusByCostId(req)==1?true:false;
    }

    @Override
    public List<QueryCostStatistics1VO> costStatistics1List(QueryCostStatistics1Req req) {
        List<QueryCostStatistics1VO> costStatistics1VOS=costDao.costStatistics1List(req);
        for (QueryCostStatistics1VO p:costStatistics1VOS){
            p.setCreateTimeStr(DateUtils.format(p.getCreateTime(),DateUtils.DATE_PATTERN));
            p.setTotalCostCreateTimeStr(DateUtils.format(p.getTotalCostCreateTime(),DateUtils.DATE_PATTERN));
            p.setInvoiceDateStr(DateUtils.format(p.getInvoiceDate(),DateUtils.DATE_PATTERN));
            switch (p.getStatus()){
                case "1":
                    p.setStatus("草稿箱");
                    break;
                case "2":
                    p.setStatus("待批箱");
                    break;
                case "3":
                    p.setStatus("已批箱");
                    break;
                case "4":
                    p.setStatus("完成箱");
                    break;
                case "5":
                    p.setStatus("垃圾箱");
                    break;
            }
            switch (p.getCostType()){
                case "1":
                    p.setCostType("直接费用");
                    break;
                case "2":
                    p.setCostType("间接费用");
                    break;
            }
        }
        return costStatistics1VOS;
    }

    @Override
    public List<QueryCostStatistics2VO> costStatistics2List(QueryCostStatistics1Req req) {
        List<QueryCostStatistics2VO> costStatistics2VOS=costDao.costStatistics2List(req);
        for (QueryCostStatistics2VO p:costStatistics2VOS) {
            if(p.getUnPaymentCost().compareTo(BigDecimal.ZERO) == 0){
                p.setCostPaymentType("已支付");
            }else if (p.getPaymentCost().compareTo(BigDecimal.ZERO)==0){
                p.setCostPaymentType("未支付");
            }else if(p.getUnPaymentCost().compareTo(BigDecimal.ZERO) == 1){
                p.setCostPaymentType("部分支付");
            }
            p.setCreateTimeStr(DateUtils.format(p.getCreateTime(),DateUtils.DATE_PATTERN));
            p.setTotalCostCreateTimeStr(DateUtils.format(p.getTotalCostCreateTime(),DateUtils.DATE_PATTERN));

            switch (p.getStatus()){
                case "1":
                    p.setStatus("草稿箱");
                    break;
                case "2":
                    p.setStatus("待批箱");
                    break;
                case "3":
                    p.setStatus("已批箱");
                    break;
                case "4":
                    p.setStatus("完成箱");
                    break;
                case "5":
                    p.setStatus("垃圾箱");
                    break;
            }
            switch (p.getCostType()){
                case "1":
                    p.setCostType("直接费用");
                    break;
                case "2":
                    p.setCostType("间接费用");
                    break;
            }


        }
        return costStatistics2VOS;
    }


    @Override
    public String findIdsByContractOrStock(String code,Integer mark) {
        List<Integer> idList = costDao.findIdsByContractOrStock(code, mark);
        String idStr = StringUtils.join(idList, ",");
        return idStr;
    }

    @Override
    public List<QueryCostRes> findCostByIds(String ids) {
        return costDao.findCostByIds(ids);
    }
}
